<template>
  <q-dialog class="my_dialog" v-model="isFlagShow">
    <q-card class="my-card q-mx-lg">
      <q-toolbar class="row items-center my_form_header">
        <div>
          {{dlgTitle}}
        </div>
        <q-space />
        <q-btn flat round dense icon="mdi-close" @click="close"/>
      </q-toolbar>
      <q-separator />
      <q-card-setion class="q-mx-sm">
        <q-scroll-area class="my-form-container">
          <div class="col q-gutter-xs">
            <q-item class="items-center">
              <q-item-label><span style="color: red">**</span>角色选择：</q-item-label>
              <q-item-section>
                <q-select
                  dense
                  outlined
                  options-dense
                  :options="roleArr"
                  v-model="param.master"
                  option-value="label"
                  emit-value
                  options-selected-class="teal"
                  @update:model-value="refreshRole"
                />
              </q-item-section>
            </q-item>
            <q-item class="items-center">
              <q-item-label><span style="color: red">**</span>权限操作：</q-item-label>
              <q-item-section>
                <q-select
                  dense
                  outlined
                  options-dense
                  :options="permissionOperateTypeArr"
                  v-model="param.operation"
                  option-value="label"
                  emit-value
                  options-selected-class="teal"
                />
              </q-item-section>
            </q-item>
            <q-item class="items-center">
              <q-item-label><span style="color: red">**</span>权限范围：</q-item-label>
              <q-item-section>
                <q-input
                  outlined
                  dense
                  type="number"
                  v-model="param.privilege"
                />
              </q-item-section>
            </q-item>
            <q-item class="items-center">
              <q-item-label><span style="color: red">**</span>权限组件：</q-item-label>
              <q-item-section>
                <q-select
                  dense
                  outlined
                  options-dense
                  :options="permissionComponentTypeArr"
                  v-model="param.fieldType"
                  option-value="label"
                  emit-value
                  options-selected-class="teal"
                  @update:model-value="refreshComponentType"
                />
              </q-item-section>
            </q-item>
            <q-item class="items-center">
              <q-item-label><span style="color: red">**</span>权限分配：</q-item-label>
              <q-item-section>
                <div class="my-tree">
                  <template v-if="isMenuTree">
                    <MenuTree
                      :nodes="mTree"
                      v-model:tick-option="myTickOption"
                    />
                  </template>
                  <template v-else>
                    <div>
                      暂无相关权限组件
                    </div>
                  </template>
                </div>
              </q-item-section>
            </q-item>
          </div>
        </q-scroll-area>
      </q-card-setion>
      <q-separator />
      <q-separator />
      <div class="q-gutter-sm my_form_footer">
        <q-btn
          unelevated
          dense
          label="提交"
          type="submit"
          color="teal-3"
          @click="onSubmit"
          style="width: 80px"
        />
        <q-btn
          unelevated
          dense
          label="重置"
          type="reset"
          color="orange-3"
          @click="onReset"
          style="width: 80px"
        />
      </div>
    </q-card>
  </q-dialog>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref, toRefs, PropType, watch, toRef, nextTick } from 'vue';
import { PermissionItem, PermissionItemVO } from './permissionModel';
import MenuTree from './PermissionTree.vue'
import { cataItem } from 'src/hook/common/useCatalogType';
import api from 'axios';
import { useMessageNotify } from 'src/hook/common/useMessageNotify';
import { sysBaseUrlAPI } from 'src/util/SysBaseConst';
import { getPermissionMenuTree } from 'src/hook/getPermissionMenuTree';
import { useCatalogTool } from 'src/hook/common/useCatalogTool';
import { isObjectEmpty } from 'src/util/utils';


export default defineComponent({
  name: 'PermissionDlg',
  components: {
    MenuTree
  },

  props: {
    itemData: {
      type: Object as PropType<PermissionItem>,
      required: true
    },

    roleArr: {
      type: Array as PropType<cataItem[]>,
      default: () => {
        return []
      }
    },
    permissionComponentTypeArr: {
      type: Array as PropType<cataItem[]>,
      default: () => {
        return []
      }
    },
    permissionOperateTypeArr: {
      type: Array as PropType<cataItem[]>,
      default: () => {
        return []
      }
    }
  },
  emits: ['submit-permission-item', 'cancel-permission-item'],
  setup (props, context) {
    //数据解构
    const {
      itemData,
      roleArr,
      permissionComponentTypeArr,
      permissionOperateTypeArr
    } = toRefs(props);

    //*********************************************************************************************
    //      hook
    //*********************************************************************************************
    const {
      mTree,
      getPermissionMenuTreeVO,
      searchPermissionMenuTreeVO
    } = getPermissionMenuTree();
    //*********************************************************************************************
    //      消息通知
    //*********************************************************************************************
    //消息通知
    const {
      showSuccessMessage,
      showMessage
    } = useMessageNotify();

    //*******************************
    //      目录操作
    //*******************************
    const {
      findCatalogId
    } = useCatalogTool();

    //*******************************
    //      表单项
    //*******************************
    //窗口显示
    let isFlagShow = ref(false);

    //窗口标题
    let dlgTitle = ref('');

    //权限树
    let isMenuTree = ref(true);
    let tickArr = ref<cataItem[]>([]);
    let myTickOption = ref<number[]>([]);


    //界面数据
    let param = ref<PermissionItemVO>({
      id: 0,
      master: '',
      fieldType: '',
      fieldTypeValue: '',
      fieldId: 0,
      fieldValue: '',
      operation: '',
      privilege: 0,
      sortCode: ''
    });

    //关闭窗口
    const close = () => {
      isFlagShow.value = false;
      onReset();
    }

    //显示窗口
    const show = (text: string) => {
      isFlagShow.value = true;
      dlgTitle.value = text;
    }

    //读取该masterId已设置权限表
    const getPermissionByMasterIdAndFieldTypeId = () => {
      let mid = findCatalogId(roleArr.value, param.value.master);
      let typeId = findCatalogId(permissionComponentTypeArr.value, param.value.fieldType);

      //查询数据库
      api.post(sysBaseUrlAPI.SYS_PERMISSION_API_LIST, {
        masterId: (mid > 0) ? mid : 0,
        fieldTypeId: (typeId > 0) ? typeId : 0
      }).then((res) => {
        if (res.data.message === 'Success') {
          tickArr.value.length = 0;
          myTickOption.value.length = 0;
          let ls: cataItem[] = res.data.data;
          ls.forEach((item) => {
            tickArr.value.push(item);
            myTickOption.value.push(item.id);
          });
        } else {
          showMessage(res.data.message);
        }
      }).catch((error) => {
        showMessage(error);
      });
    }

    //提交窗口
    const onSubmit = () => {
      //隐藏
      isFlagShow.value = false;

      //基本信息
      let mid = findCatalogId(roleArr.value, param.value.master);
      let typeId = findCatalogId(permissionComponentTypeArr.value, param.value.fieldType);
      let r: PermissionItem = {
        id: param.value.id,
        masterId: mid > 0 ? mid : 0,
        fieldTypeId: typeId > 0 ? typeId : 0,
        fieldTypeValue: param.value.fieldType,
        fieldId: 0,
        fieldValue: param.value.fieldValue,
        operationId: findCatalogId(permissionOperateTypeArr.value, param.value.operation),
        privilege: param.value.privilege,
        sortCode: '',
        createTime: '',
        createUserId: 0,
        updateTime: '',
        updateUserId: 0
      };

      //勾选列表
      getTickInfo();

      //提交保存
      api.post(sysBaseUrlAPI.SYS_PERMISSION_API_SAVE, {
        record: r,
        list: tickArr.value
      }).then((res) => {
        if (res.data.message === 'Success') {
          showSuccessMessage('权限管理');
          context.emit('submit-permission-item', 1);
        } else {
          showMessage(res.data.message);
        }
      }).catch((error) => {
        showMessage(error);
      })
    }

    //重置
    const onReset = () => {
      if (param.value) {
        param.value.master = (roleArr.value.length > 0) ? roleArr.value[0].label : '';
        param.value.fieldType = (permissionComponentTypeArr.value.length > 0) ? permissionComponentTypeArr.value[0].label : '';
        param.value.fieldTypeValue = param.value.fieldType;
        param.value.fieldId = 0;
        param.value.fieldValue = '';
        param.value.operation = (permissionOperateTypeArr.value.length > 0) ?  permissionOperateTypeArr.value[0].label : '';
        param.value.privilege = 0;
        param.value.sortCode = '';
      }
    }

    //更新角色信息
    const refreshRole = () => {
      getPermissionByMasterIdAndFieldTypeId();
    }

    //更新组件树
    const refreshComponentType = () => {
      if (param.value.fieldType === '菜单') {
        isMenuTree.value = true;
        getPermissionMenuTree();
      } else {
        isMenuTree.value = false;
      }

      getPermissionByMasterIdAndFieldTypeId();
    }

    //插入勾选队列
    const addTickQue = (id: number) => {
      if (!myTickOption.value.includes(id)) {
        myTickOption.value.push(id);
      }
    }

    //勾选信息封装
    const getTickInfo = () => {
      tickArr.value.length = 0;

      //根据子节点信息，将父节点信息也进行勾选
      mTree.value.forEach((item) => {
        if ((item.children) && (item.children.length > 0)) {
          for (let i = 0; i < item.children.length; i++) {
            if (myTickOption.value.includes(item.children[i].id)) {
              addTickQue(item.id);
              break;
            }
          }
        }
      });

      //封装数据
      myTickOption.value.forEach((item) => {
        let name = searchPermissionMenuTreeVO(mTree.value, item);
        if (name) {
          tickArr.value.push({
            id: item,
            label: name
          });
        }
      });
    }


    //*******************************
    //      启动模块
    //*******************************
    //初始化
    const init = () => {
      //默认值
      if (!isObjectEmpty(itemData.value)) {
        param.value.id = itemData.value.id;
        param.value.master = (roleArr.value.length > 0) ? roleArr.value[0].label : '';
        param.value.fieldType = (permissionComponentTypeArr.value.length > 0) ? permissionComponentTypeArr.value[0].label : '';
        param.value.fieldTypeValue = param.value.fieldType;
        param.value.fieldId = itemData.value.fieldId;
        param.value.fieldValue = itemData.value.fieldValue;
        param.value.operation = (permissionOperateTypeArr.value.length > 0) ?  permissionOperateTypeArr.value[0].label : '';
        param.value.privilege = itemData.value.privilege;
        param.value.sortCode = itemData.value.sortCode;
      }

      //菜单树
      getPermissionMenuTreeVO();
    }


    //启动挂载组件
    onMounted(() => {
      init();
      nextTick(() => {
        getPermissionByMasterIdAndFieldTypeId();
      })
    })

    return {
      roleArr,
      permissionComponentTypeArr,
      permissionOperateTypeArr,
      mTree,
      isFlagShow,
      dlgTitle,
      param,
      isMenuTree,
      tickArr,
      myTickOption,
      init,
      close,
      show,
      onSubmit,
      onReset,
      refreshRole,
      refreshComponentType
    }
  }
})
</script>

<style lang="scss" scoped>
.my-card {
  alignment: center;
  width: 600px;
  max-width: 800px;

  .my-form-container {
    text-align: center;
    padding: 5px 50px 5px 50px;
    height: 350px;

    .my-tree {
      border:1px solid #d4c6c6;
    }
  }
}
</style>
